package com.pdd.util;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

/**
 * @创建时间: 2018/8/16 - 10:59
 * @编写人员: 丷教皇
 * @文件描述:
 */
public class IPUtil {

    /**
     * 从请求中获取用户真实IP地址。
     * @param request 用户请求。
     * @return IP地址。
     */
    public static String getRealIP(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");

        if(null == ip || 0 == ip.length() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(null == ip || 0 == ip.length() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(null == ip || 0 == ip.length() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if(null == ip || 0 == ip.length() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if(Pattern.matches("/\\d+\\.\\d+\\.\\d+\\.\\d+/", ip)){
            return ip;
        }

        return "127.0.0.1";

    }

}
